import { Request, Response } from 'express';
import { tagService } from '../services/tagService';
import { CreateTagRequest, UpdateTagRequest } from '../types/tag';
import { ApiResponse, HttpStatus } from '../types/api';
import { validationResult } from 'express-validator';

/**
 * 标签控制器类
 * 处理标签相关的HTTP请求
 */
export class TagController {
  /**
   * 获取所有标签（支持分页和搜索）
   * GET /api/tags
   */
  async getAllTags(req: Request, res: Response): Promise<void> {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const search = req.query.search as string;
      const sortBy = req.query.sortBy as string || 'createdAt';
      const sortOrder = req.query.sortOrder as string || 'desc';

      const result = await tagService.getAllTags({
        page,
        limit,
        search,
        sortBy,
        sortOrder
      });

      const response: ApiResponse = {
        success: true,
        data: result.tags,
        pagination: {
          page: result.page,
          limit: result.limit,
          total: result.total,
          totalPages: result.totalPages
        },
        message: '获取标签列表成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取标签列表失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 根据ID获取单个标签
   * GET /api/tags/:id
   */
  async getTagById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const tag = await tagService.getTagById(id);

      if (!tag) {
        const response: ApiResponse = {
          success: false,
          error: '标签不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      const response: ApiResponse = {
        success: true,
        data: tag,
        message: '获取标签成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取标签失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 创建新标签
   * POST /api/tags
   */
  async createTag(req: Request, res: Response): Promise<void> {
    try {
      // 检查验证错误
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const response: ApiResponse = {
          success: false,
          error: '输入数据验证失败',
          errors: errors.array().map((err: any) => ({
            field: err.path,
            message: err.msg
          }))
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const tagData: CreateTagRequest = req.body;
      
      // 检查标签名是否已存在
      const existingTag = await tagService.getTagByName(tagData.name);
      if (existingTag) {
        const response: ApiResponse = {
          success: false,
          error: '标签名已存在'
        };
        res.status(HttpStatus.CONFLICT).json(response);
        return;
      }

      const newTag = await tagService.createTag(tagData);

      const response: ApiResponse = {
        success: true,
        data: newTag,
        message: '创建标签成功'
      };

      res.status(HttpStatus.CREATED).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `创建标签失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 更新标签
   * PUT /api/tags/:id
   */
  async updateTag(req: Request, res: Response): Promise<void> {
    try {
      // 检查验证错误
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const response: ApiResponse = {
          success: false,
          error: '输入数据验证失败',
          errors: errors.array().map((err: any) => ({
            field: err.path,
            message: err.msg
          }))
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const { id } = req.params;
      const updateData: UpdateTagRequest = req.body;

      // 检查标签是否存在
      const existingTag = await tagService.getTagById(id);
      if (!existingTag) {
        const response: ApiResponse = {
          success: false,
          error: '标签不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      // 如果更新名称，检查新名称是否已存在
      if (updateData.name && updateData.name !== existingTag.name) {
        const tagWithSameName = await tagService.getTagByName(updateData.name);
        if (tagWithSameName) {
          const response: ApiResponse = {
            success: false,
            error: '标签名已存在'
          };
          res.status(HttpStatus.CONFLICT).json(response);
          return;
        }
      }

      const updatedTag = await tagService.updateTag(id, updateData);

      const response: ApiResponse = {
        success: true,
        data: updatedTag,
        message: '更新标签成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `更新标签失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 删除标签
   * DELETE /api/tags/:id
   */
  async deleteTag(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      // 检查标签是否存在
      const existingTag = await tagService.getTagById(id);
      if (!existingTag) {
        const response: ApiResponse = {
          success: false,
          error: '标签不存在'
        };
        res.status(HttpStatus.NOT_FOUND).json(response);
        return;
      }

      await tagService.deleteTag(id);

      const response: ApiResponse = {
        success: true,
        message: '删除标签成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `删除标签失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 批量删除标签
   * DELETE /api/tags
   */
  async batchDeleteTags(req: Request, res: Response): Promise<void> {
    try {
      const { ids } = req.body;

      if (!Array.isArray(ids) || ids.length === 0) {
        const response: ApiResponse = {
          success: false,
          error: '请提供有效的标签ID数组'
        };
        res.status(HttpStatus.BAD_REQUEST).json(response);
        return;
      }

      const deletedCount = await tagService.batchDeleteTags(ids);

      const response: ApiResponse = {
        success: true,
        data: { deletedCount },
        message: `成功删除 ${deletedCount} 个标签`
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `批量删除标签失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }

  /**
   * 获取标签统计信息
   * GET /api/tags/stats
   */
  async getTagStats(req: Request, res: Response): Promise<void> {
    try {
      const stats = await tagService.getTagStats();

      const response: ApiResponse = {
        success: true,
        data: stats,
        message: '获取标签统计信息成功'
      };

      res.status(HttpStatus.OK).json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: `获取标签统计信息失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(response);
    }
  }
}

// 导出控制器实例
export const tagController = new TagController();